package mailServlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.MailSendDAO;
import dto.UserDTO;

@SuppressWarnings("serial")
public class DeleteForeverServlet extends HttpServlet {

	public DeleteForeverServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.execute(request, response);
		

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.execute(request, response);

	}

	public void execute(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		MailSendDAO mdao=new MailSendDAO();
		UserDTO udto=(UserDTO) request.getSession().getAttribute("USER");
	    String fileName=request.getSession().getServletContext().getRealPath("\\")+"AllUsers/"+udto.getUserName();
		String []dates=request.getParameterValues("one");
		String n=request.getParameter("n");
		String sql=null;
		if("1".equals(n)){
			if(delete(fileName+"/delete", dates)){
				sql="update tb_send set receive_state='4' where (send_fromname='"+udto.getUserName()+"' or send_toname='"+udto.getUserName()+"') and send_date=?";
				if(mdao.update(sql, dates)){
					response.sendRedirect("MailHaveDeletedServlet");
				}
			}
		}else{
			if(delete(fileName+"/ready", dates)){
				sql="update tb_send set send_state='4' where send_fromname='"+udto.getUserName()+"' and send_date=?";
				if(mdao.update(sql, dates)){
					response.sendRedirect("MailReadyServlet");
				}
			}
		}
	}
	
	private boolean delete(String fromFile,String []dates){
		boolean flag=false;
		String deleName=null;
		for(String date:dates){
			deleName=fromFile+"/"+date+".txt";
			File file1=new File(deleName);
			file1.delete();
		}
		flag=true;
		return flag;
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
